<template>
  <div class="cart-page">
    <div class="container">
      <!-- 页面标题 -->
      <div class="page-header">
        <h1 class="page-title">購物車</h1>
        <div class="cart-info">
          <span class="item-count">{{ cartStore.totalItems }}件產品</span>
        </div>
      </div>

      <!-- 购物车内容 -->
      <div class="cart-content" v-if="cartStore.items.length > 0">
        <!-- 购物车列表 -->
        <div class="cart-list">
          <!-- 列表头部 -->
          <div class="cart-header">
            <el-checkbox
                :model-value="allChecked"
                @change="handleSelectAll"
                :indeterminate="indeterminate"
            >
              全選
            </el-checkbox>
            <span class="header-text">產品信息</span>
            <span class="header-text">單價</span>
            <span class="header-text">數量</span>
            <span class="header-text">金額</span>
            <span class="header-text">操作</span>
          </div>

          <!-- 购物车產品列表 -->
          <div
              v-for="item in cartStore.items"
              :key="`${item.id}-${item.specs}`"
              class="cart-item"
          >
            <div class="item-checkbox">
              <el-checkbox
                  :model-value="item.checked"
                  @change="() => cartStore.toggleItemCheck(item.id, item.specs)"
              />
            </div>

            <div class="item-info">
              <div class="item-image">
                <img :src="item.image" :alt="item.name"/>
              </div>
              <div class="item-details">
                <h3 class="item-name">{{ item.name }}</h3>
                <p class="item-specs" v-if="item.specs">{{ item.specs }}</p>
                <div class="item-tags">
                  <el-tag size="small" type="danger">正品保證</el-tag>
                  <el-tag size="small" type="success">包郵</el-tag>
                </div>
              </div>
            </div>

            <div class="item-price">
              <span class="current-price"><Currency/>{{ formatPrice(item.price) }}</span>
            </div>

            <div class="item-quantity">
              <div class="quantity-selector">
                <button
                    class="quantity-btn quantity-btn-decrease"
                    @click="decreaseQuantity(item)"
                    :disabled="item.quantity <= 1"
                >
                  <el-icon>
                    <Minus/>
                  </el-icon>
                </button>
                <input
                    class="quantity-input"
                    v-model.number="item.quantity"
                    @input="(e) => validateQuantity(item, e)"
                    @blur="(e) => validateQuantity(item, e)"
                    type="number"
                    :min="1"
                    :max="99"
                />
                <button
                    class="quantity-btn quantity-btn-increase"
                    @click="increaseQuantity(item)"
                    :disabled="item.quantity >= 99"
                >
                  <el-icon>
                    <Plus/>
                  </el-icon>
                </button>
              </div>
            </div>

            <div class="item-total">
              <span class="total-price"><Currency/>{{ formatPrice(item.price * item.quantity) }}</span>
            </div>

            <div class="item-actions">
              <el-button
                  type="text"
                  size="small"
                  @click="cartStore.removeFromCart(item.id, item.specs)"
              >
                删除
              </el-button>
            </div>
          </div>
        </div>

        <!-- 推荐產品 -->
        <div class="recommended-section">
          <h3 class="section-title">爲你推薦</h3>
          <div class="recommended-products">
            <div
                v-for="product in recommendedProducts"
                :key="product.id"
                class="recommended-item"
                @click="$router.push(`/product/${product.id}`)"
            >
              <img :src="product.image" :alt="product.name"/>
              <div class="recommended-info">
                <el-tooltip :content="product.name" placement="top">
                  <h4 class="recommended-name">{{ product.name }}</h4>
                </el-tooltip>
                <div class="recommended-price">
                  <Currency/>
                  {{ product.price.toFixed(2) }}
                </div>
              </div>
              <el-button
                  type="primary"
                  size="small"
                  @click.stop="addRecommendedToCart(product)"
              >
                加入購物車
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 空购物车 -->
      <div class="empty-cart" v-else>
        <el-empty
            description="購物車是空的"
            :image-size="200"
        >
          <template #image>
            <div class="empty-image">
              <el-icon size="120" color="#ddd">
                <ShoppingCart/>
              </el-icon>
            </div>
          </template>
          <el-button type="primary" @click="$router.push('/')">
            去首页逛逛
          </el-button>
        </el-empty>
      </div>

      <!-- 底部结算栏 -->
      <div class="cart-footer" v-if="cartStore.items.length > 0">
        <div class="footer-left">
          <el-checkbox
              :model-value="allChecked"
              @change="handleSelectAll"
              :indeterminate="indeterminate"
          >
            全選
          </el-checkbox>
          <el-button
              type="text"
              @click="deleteSelected"
              :disabled="cartStore.checkedItems.length === 0"
          >
            刪除選中產品
          </el-button>
        </div>

        <div class="footer-right">
          <div class="total-info">
            <span class="selected-count">已選擇 {{ cartStore.checkedItemsCount }} 件產品</span>
            <div class="total-price">
              <span class="total-label">合計:</span>
              <span class="total-amount"><Currency/>{{ cartStore.totalPrice.toFixed(2) }}</span>
            </div>
          </div>
          <el-button
              type="danger"
              size="large"
              @click="checkout"
              :disabled="cartStore.checkedItems.length === 0"
          >
            結算 ({{ cartStore.checkedItems.length }})
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, computed, onMounted} from 'vue'
import {useRouter} from 'vue-router'
import {ElMessage, ElMessageBox} from 'element-plus'
import {ShoppingCart, Minus, Plus} from '@element-plus/icons-vue'
import {useCartStore} from '@/store'
import {formatPrice} from '@/utils/formatPrice.ts'
import {fetchRan} from "@/request/req.ts";
import {commonStore} from '@/store/common.ts'
import Currency from "@/components/common/Currency.vue";

const common = commonStore()

const router = useRouter()
const cartStore = useCartStore()

const recommendedProducts = ref<any[]>([])

const serverUrl = computed(() => {
  const item = common.getItemById(1)
  return item?.value
})
// 计算全选状态
const allChecked = computed(() => {
  return cartStore.items.length > 0 && cartStore.items.every(item => item.checked)
})

// 计算半选状态
const indeterminate = computed(() => {
  const checkedItems = cartStore.items.filter(item => item.checked)
  return checkedItems.length > 0 && checkedItems.length < cartStore.items.length
})

// 处理全选/取消全选
const handleSelectAll = (checked: boolean) => {
  cartStore.toggleAllCheck(checked)
}

// 删除选中產品
const deleteSelected = async () => {
  try {
    await ElMessageBox.confirm(
        '确定要删除选中的產品吗？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const selectedItems = cartStore.checkedItems
    selectedItems.forEach(item => {
      cartStore.removeFromCart(item.id, item.specs)
    })

    ElMessage.success('產品已删除')
  } catch {
    // 用户取消删除
  }
}
/**
 * 获取随机產品
 */
const loadRandomProducts = async () => {
  try {
    const res = await fetchRan({id: 6})
    if (res.Success === "true" && res.GoodsList && Array.isArray(res.GoodsList)) {
      // 将API返回的数据映射到推荐產品格式
      recommendedProducts.value = res.GoodsList.map((item: any) => ({
        id: item.Id,
        name: item.GoodsName,
        price: item.Pirce,
        image: `${serverUrl.value}/images/UpLoadPic/${item.PicUrls}`,
        specs: item.Format,
        description: item.ProductDescription
      }))
    }
  } catch (error) {
    console.error('获取推荐產品失败:', error)
    ElMessage.error('获取推荐產品失败')
  }
}

// 添加推荐產品到购物车
const addRecommendedToCart = (product: any) => {
  cartStore.addToCart({
    id: product.id,
    name: product.name,
    price: product.price,
    image: product.image,
    specs: product.specs || undefined,
    skuId: undefined,
    skuData: undefined
  })
  ElMessage.success('已添加到購物車')
}

// 结算 - 直接跳转到结算页面
// 数量选择器方法
const decreaseQuantity = (item: any) => {
  if (item.quantity > 1) {
    item.quantity--
    cartStore.updateQuantity(item.id, item.quantity, item.specs)
  }
}

const increaseQuantity = (item: any) => {
  if (item.quantity < 99) {
    item.quantity++
    cartStore.updateQuantity(item.id, item.quantity, item.specs)
  }
}

const validateQuantity = (item: any, event: any) => {
  const value = parseInt(event.target.value)

  if (isNaN(value) || value < 1) {
    item.quantity = 1
  } else if (value > 99) {
    item.quantity = 99
  } else {
    item.quantity = value
  }

  cartStore.updateQuantity(item.id, item.quantity, item.specs)
}

const checkout = () => {
  const result = cartStore.checkout()
  if (result.success && result.total !== undefined) {
    // 将选中的產品信息存储到sessionStorage，供结算页面使用
    sessionStorage.setItem('checkoutItems', JSON.stringify(result.items))
    sessionStorage.setItem('checkoutTotal', result.total.toString())

    // 直接跳转到结算页面
    router.push('/checkout')
  } else {
    ElMessage.warning(result.message || '結算失败')
  }
}

onMounted(() => {
  // 从本地存储加载购物车数据
  cartStore.loadFromLocalStorage()
  // 加载推荐產品
  loadRandomProducts()
})
</script>

<style scoped>
.cart-page {
  background: var(--bg-tertiary);
  min-height: 100vh;
  padding: var(--spacing-xl) 0;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  font-size: var(--font-size-2xl);
  color: var(--text-primary);
  margin: 0;
}

.cart-info {
  color: #666;
  font-size: 14px;
}

.item-count {
  background: var(--gradient-primary);
  color: var(--text-light);
  padding: var(--spacing-xs) var(--spacing-sm);
  border-radius: var(--radius-rounded);
  font-size: var(--font-size-xs);
}

/* 购物车内容 */
.cart-content {
  background: var(--bg-primary);
  border-radius: var(--radius-lg);
  overflow: hidden;
  margin-bottom: var(--spacing-xl);
  border: 1px solid var(--border-primary);
  box-shadow: var(--shadow-card);
}


.cart-header {
  display: grid;
  grid-template-columns: auto 1fr auto auto auto auto;
  gap: var(--spacing-xl);
  align-items: center;
  padding: var(--spacing-lg) var(--spacing-xl);
  background: var(--bg-primary);
  font-weight: var(--font-weight-semibold);
  color: var(--text-primary);
  border-bottom: 1px solid var(--border-primary);
}

.header-text {
  color: var(--text-primary);
  text-align: center;
  font-size: var(--font-size-sm);
}


.cart-item {
  display: grid;
  grid-template-columns: auto 1fr auto auto auto auto;
  gap: var(--spacing-xl);
  align-items: center;
  padding: var(--spacing-xl);
  transition: var(--transition-all);
  border-bottom: 1px solid var(--border-secondary);
}

.cart-item:hover {
  background: var(--primary-bg);
}

.cart-item:last-child {
  border-bottom: none;
}

.item-info {
  display: flex;
  gap: 12px;
  align-items: flex-start;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: var(--radius-sm);
  overflow: hidden;
  flex-shrink: 0;
  border: 1px solid var(--border-secondary);
  box-shadow: var(--shadow-soft);
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-details {
  flex: 1;
}

.item-name {
  font-size: var(--font-size-base);
  color: var(--text-primary);
  margin-bottom: var(--spacing-sm);
  line-height: 1.4;
}

.item-specs {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  margin-bottom: var(--spacing-sm);
}

.item-tags {
  display: flex;
  gap: 4px;
}

.item-price {
  text-align: center;
}

.current-price {
  font-size: var(--font-size-base);
  color: var(--primary-color);
  font-weight: var(--font-weight-semibold);
}

.item-quantity {
  text-align: center;
}

.quantity-selector {
  display: flex;
  align-items: center;
  width: 120px;
  height: 32px;
  border: 1px solid var(--border-dark);
  border-radius: var(--radius-sm);
  background: var(--bg-primary);
  overflow: hidden;
  margin: 0 auto;
}

.quantity-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: var(--bg-secondary);
  color: var(--text-primary);
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: var(--transition-all);
  outline: none;
  padding: 0;
  margin: 0;
}

.quantity-btn:hover:not(:disabled) {
  background: var(--primary-color);
  color: var(--text-light);
}

.quantity-btn:disabled {
  background: var(--bg-primary);
  color: var(--text-muted);
  cursor: not-allowed;
}

.quantity-btn-decrease {
  border-top-left-radius: 3px;
  border-bottom-left-radius: 3px;
}

.quantity-btn-increase {
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
}

.quantity-input {
  flex: 1;
  height: 30px;
  border: none;
  background: var(--bg-primary);
  color: var(--text-primary);
  text-align: center;
  font-size: var(--font-size-sm);
  outline: none;
  margin: 0;
  padding: 0 4px;
  -moz-appearance: textfield; /* 隐藏 Firefox 的数字输入框箭头 */
}

.quantity-input::-webkit-outer-spin-button,
.quantity-input::-webkit-inner-spin-button {
  -webkit-appearance: none; /* 隐藏 Chrome/Safari 的数字输入框箭头 */
  margin: 0;
}

.quantity-input:focus {
  background: var(--bg-primary);
  color: var(--text-primary);
}

.item-total {
  text-align: center;
}

.total-price {
  font-size: var(--font-size-base);
  color: var(--primary-color);
  font-weight: var(--font-weight-semibold);
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 4px;
  align-items: center;
}

/* 推荐產品 */
.recommended-section {
  padding: var(--spacing-xl);
  border-top: 1px solid var(--border-secondary);
}

.section-title {
  font-size: var(--font-size-lg);
  color: var(--text-primary);
  margin-bottom: var(--spacing-lg);
}

.recommended-products {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: var(--spacing-lg);
}

.recommended-item {
  background: var(--bg-secondary);
  border-radius: var(--radius-lg);
  padding: 0;
  cursor: pointer;
  transition: var(--transition-all);
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
  border: 1px solid var(--border-secondary);
}

.recommended-item:hover {
  box-shadow: var(--shadow-medium);
  transform: translateY(-2px);
  border-color: var(--primary-color);
}

  .recommended-item img {
    width: 100%;
    height: 200px;
    object-fit: fill;
    display: block;
    flex-shrink: 0;
  }

  .recommended-info {
    margin-bottom: 8px;
  }

  .recommended-name {
    width: 120px;
    font-size: var(--font-size-xs);
    color: var(--text-primary);
    margin-bottom: var(--spacing-xs);
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }

  .recommended-price {
    font-size: var(--font-size-sm);
    color: var(--primary-color);
    font-weight: var(--font-weight-semibold);
  }

  /* 空购物车 */

  .empty-cart {
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: 60px var(--spacing-xl);
    text-align: center;
    border: 1px solid var(--border-primary);
    box-shadow: var(--shadow-card);
  }

  .empty-image {
    margin-bottom: 20px;
  }

  /* 底部结算栏 */

  .cart-footer {
    position: sticky;
    bottom: 0;
    background: var(--bg-primary);
    border-radius: var(--radius-lg);
    padding: var(--spacing-xl);
    box-shadow: var(--shadow-medium);
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid var(--border-primary);
  }

  .footer-left {
    display: flex;
    align-items: center;
    gap: var(--spacing-xl);
  }

  .footer-right {
    display: flex;
    align-items: center;
    gap: var(--spacing-xl);
  }

  .total-info {
    text-align: right;
  }

  .selected-count {
    display: block;
    font-size: var(--font-size-xs);
    color: var(--text-secondary);
    margin-bottom: var(--spacing-xs);
  }

  .total-price {
    display: flex;
    align-items: baseline;
    gap: var(--spacing-sm);
  }

  .total-label {
    font-size: var(--font-size-sm);
    color: var(--text-primary);
  }

  .total-amount {
    font-size: var(--font-size-2xl);
    color: var(--primary-color);
    font-weight: var(--font-weight-bold);
  }

  .checkout-item img {
    width: 50px;
    height: 50px;
    object-fit: cover;
    border-radius: 4px;
  }


  /* 响应式设计 */
  @media (max-width: 1024px) {
    .recommended-products {
      grid-template-columns: repeat(4, 1fr);
    }
  }

  @media (max-width: 768px) {
    .container {
      padding: 0 12px;
    }

    .cart-header {
      display: none;
    }

    .cart-item {
      grid-template-columns: 1fr;
      gap: 12px;
      padding: 16px;
    }

    .item-info {
      order: 1;
    }

    .item-checkbox {
      order: 0;
      position: absolute;
      top: 16px;
      left: 16px;
    }

    .item-price,
    .item-quantity,
    .item-total {
      order: 2;
      text-align: left;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .item-price::before {
      content: '單價: ';
      color: #666;
    }

    .item-total::before {
      content: '小計: ';
      color: #666;
    }

    .item-actions {
      order: 3;
      flex-direction: row;
      justify-content: flex-start;
    }

    .cart-footer {
      flex-direction: column;
      gap: 16px;
      align-items: stretch;
    }

    .footer-left,
    .footer-right {
      justify-content: center;
    }

    /* 手机端推荐產品优化 */
    .recommended-section {
      padding: 16px;
      border-top: 1px solid rgba(240, 240, 240, 0.2);
    }

    .section-title {
      font-size: 16px;
      margin-bottom: 12px;
      text-align: center;
    }

    .recommended-products {
      display: flex;
      overflow-x: auto;
      gap: 12px;
      padding-bottom: 8px;
      -webkit-overflow-scrolling: touch;
    }

    .recommended-products::-webkit-scrollbar {
      height: 4px;
    }

    .recommended-products::-webkit-scrollbar-track {
      background: rgba(255, 255, 255, 0.1);
      border-radius: 2px;
    }

    .recommended-products::-webkit-scrollbar-thumb {
      background: var(--primary-color);
      border-radius: 2px;
    }

    .recommended-item {
      flex: 0 0 140px;
      width: 140px;
      background: #34495e;
      border-radius: 8px;
      padding: 8px;
      border: 1px solid transparent;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      overflow: hidden;
      box-sizing: border-box;
    }

    .recommended-item:hover {
      border-color: var(--primary-color);
      box-shadow: var(--shadow-soft);
      transform: none;
    }

    .recommended-item img {
      width: 100%;
      height: 100px;
      object-fit: cover;
      border-radius: 4px;
      margin-bottom: 6px;
      display: block;
      flex-shrink: 0;
    }

    .recommended-info {
      flex: 1;
      margin-bottom: 6px;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
    }

    .recommended-name {
      width: 100%;
      font-size: 11px;
      line-height: 1.2;
      margin-bottom: 4px;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      min-height: 26px;
    }

    .recommended-price {
      font-size: var(--font-size-xs);
      font-weight: var(--font-weight-semibold);
      color: var(--primary-color);
    }

    .recommended-item .el-button {
      width: 100%;
      height: 28px;
      font-size: 10px;
      padding: 0;
    }
  }

  @media (max-width: 480px) {
    .recommended-section {
      padding: 12px;
    }

    .section-title {
      font-size: 14px;
      margin-bottom: 10px;
    }

    .recommended-products {
      gap: 8px;
    }

    .recommended-item {
      flex: 0 0 120px;
      width: 120px;
      padding: 6px;
      overflow: hidden;
      box-sizing: border-box;
    }

    .recommended-item img {
      height: 80px;
      margin-bottom: 4px;
      display: block;
      flex-shrink: 0;
    }

    .recommended-info {
      margin-bottom: 4px;
    }

    .recommended-name {
      font-size: 10px;
      min-height: 24px;
    }

    .recommended-price {
      font-size: 11px;
    }

    .recommended-item .el-button {
      height: 24px;
      font-size: 9px;
    }

    .total-amount {
      font-size: 20px;
    }
  }
</style>
